import {Component, OnInit, Output, EventEmitter} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {BladeContainerBase} from '../../../../shared/blade/blade-container-base';
import {FormBuilder, FormGroup, Validators, FormControl} from '@angular/forms';
import {BladeData} from '../../../../shared/blade/blade-data';
import {Blade} from '../../../../shared/blade/blade.model';
import {Command} from '../../../../shared/toolbar.service';
import {Tag} from '../../../../entity/tag.model';
import {DialogResult} from '../../../../shared/dialog.service';
import {Setofvalue} from '../../../../entity/setofvalue.model';
import {TagService} from '../../../../service/tag.service';
import {MyValidators} from '../../../../utils/validator/rang';
import {List} from 'linqts';
import {ApplicationService} from '../../../../service/application.service';
import {TurbComponent} from '../../../../entity/turbcomponent.model';
import {TurbcomponentService} from '../../../../service/turbcomponent.service';

@Component({
  selector: 'app-tag-edit',
  templateUrl: './tag-edit.component.html',
  styleUrls: ['./tag-edit.component.css'],
})

export class TagEditComponent extends BladeContainerBase<Tag> {
  tagForm: {};
  turbComponentList: TurbComponent[];
  checkBox: any[] = [];
  tagSets: Setofvalue[];
  tagTypes: Setofvalue[];
  tagTypeId: string;
  oldTagTypeId: string;
  // tagDefinition = false;
  @Output() clearText = new EventEmitter<boolean>()

  constructor(
    private fb: FormBuilder,
    private tagService: TagService,
    public application: ApplicationService,
    private turbcomponentService: TurbcomponentService,
  ) {
    super(fb);
    this.tagSets = this.application.setKeyDict['TagSet'];
    this.tagTypes = this.application.setKeyDict['tagtype'];

  }

  // tslint:disable-next-line:use-life-cycle-interface
  ngOnInit() {
    this.tagSets.forEach((value: Setofvalue, i: number) => {
      this.checkBox[value.valueCode] = false;
    });

    this.turbComponentList = [...this.parentEntity];
    if (!this.isNew) {
      this.commands = [
        // tslint:disable-next-line:max-line-length
        new Command('save', '保存', 'fa fa-save', 'setofkey:update', (blade) => this.exeSaveChange(blade), (blade) => this.canSaveChange(blade)),
        new Command('reset', '重置', 'fa fa-save', 'setofkey:reset', (blade) => this.exeReset(blade), (blade) => this.canReset(blade)),
      ];
      const arr = this.currentEntity.tagSet.split('|');
      for (let i = 0; i < arr.length; i++) {
        this.tagSets.forEach((v: Setofvalue, index: number) => {
          if (arr[i] === v.valueCode) {
            this.checkBox[arr[i]] = true;
          }
        });

        // this.tagTypes.forEach((v: Setofvalue, index: number) => {
        //     if (this.currentEntity.tagType === v.valueCode) {
        //         this.checkBox[this.currentEntity.tagType] = true;
        //     }
        // });
      }
      this.oldTagTypeId = this.tagTypeId = this.currentEntity.tagType;
      // this.tagDefinition = !this.currentEntity.tagDefinition;

    } else {
      this.currentEntity = new Tag(0, '', '', '', '', '', '', '', '', 1, '');
    }
    this.tagForm = {
      tagName: this.currentEntity.tagName,
      tagCode: this.currentEntity.tagCode,
      tagDesc: this.currentEntity.tagDesc,
      tagId: this.currentEntity.tagId,
      tagKey: this.currentEntity.tagKey,
      tagKind: this.currentEntity.tagKind,
      tagMax: this.currentEntity.tagMax,
      tagMin: this.currentEntity.tagMin,
      tagUnit: this.currentEntity.tagUnit,
      tagSet: this.currentEntity.tagSet,
      turbComponentId: this.currentEntity.turbComponentId,
      tagType: this.currentEntity.tagType
    };
    this.tagSets.forEach((value, i) => {
      this.tagForm[value.valueCode] = this.checkBox[value.valueCode];
    });

    super.ngOnInit();
  }

  /**
   * 初始化数据
   *
   *
   * @memberof TagEditComponent
   */
  initData(): any | Observable<any> | Promise<any> {
    this.formPatchValue(this.tagForm);
  }

  exeSaveChange(blade: any): void {
    this.saveChange();
  }

  canSaveChange(blade: any): boolean {
    // return (this.hasChange() && !this.hasError()) || this.tagDefinition == this.currentEntity.tagDefinition;
    return (this.hasChange() && !this.hasError());
  }

  exeReset(blade: any): void {
    // this.tagDefinition = !this.currentEntity.tagDefinition;
    return this.formGroup.reset(this.tagForm);
  }

  canReset(blade: any): boolean {
    // return this.tagDefinition == this.currentEntity.tagDefinition || this.hasChange();
    return this.hasChange();
  }

  createForm() {

    const obj: {} = {
      'tagName': [this.currentEntity.tagName,
        [
          Validators.required,
          Validators.pattern('^[\\S]+$'),
          Validators.maxLength(50),
        ], (control: FormControl): any => this.tagAsnyValidator(control, 'tagName', this.currentEntity.tagName)
      ],
      'tagDesc': [this.currentEntity.tagDesc,
        [
          Validators.maxLength(100),
        ]
      ],
      'tagCode': [this.currentEntity.tagCode,
        [
          Validators.required,
          Validators.pattern('^[a-zA-Z0-9]+$'),
          Validators.maxLength(50),
        ]
      ],
      'tagKey': [this.currentEntity.tagKey,
        [
          Validators.required,
          Validators.pattern('^[a-zA-Z0-9]+$'),
          Validators.maxLength(50),
        ], (control: FormControl): any => this.tagAsnyValidator(control, 'tagKey', this.currentEntity.tagKey)
      ],
      'tagUnit': [this.currentEntity.tagUnit,
        [
          Validators.maxLength(20),
        ]
      ],
      'turbComponentId': [this.currentEntity.turbComponentId,
      ],
      'tagKind': [this.currentEntity.tagKind,
      ],
      'tagMin': [this.currentEntity.tagMin,
        [
          MyValidators.maxNum(65536)
        ]
      ],
      'tagMax': [this.currentEntity.tagMax,
        [
          MyValidators.maxNum(65536)
        ]
      ],
      'tagType': [this.currentEntity.tagType,
        [
          MyValidators.maxNum(65536)
        ]
      ],
    };
    this.tagSets.forEach((value, i) => {
      obj[value.valueCode] = this.checkBox[value.valueCode];
    });
    this.formGroup = this.fromBuider.group(obj);
  }

  /**
   * 设置表单错误对象
   *
   *
   * @memberof BladeContainerBase
   */
  setFormError(): void {
    this.formErrors = {
      'tagName': '',
      'tagDesc': '',
      'tagCode': '',
      'tagKey': '',
      'tagUnit': '',
      'turbComponentId': '',
      'tagMin': '',
      'tagMax': '',
      'tagType': '',
    };
  }

  /**
   * 设置表单验证信息
   *
   *
   * @memberof BladeContainerBase
   */
  setValidationMessages(): void {
    this.validationMessages = {
      'tagName': {
        'required': '测点名称不能为空。',
        'pattern': '测点名称不能为空。',
        'maxlength': '测点名称不能多于50个字符长度。',
        'exist': '测点名称已存在。',
      },
      'tagDesc': {
        'maxlength': '测点描述不能多于100个字符长度。',
      },
      'tagCode': {
        'required': '测点编码不能为空。',
        'pattern': '测点编码必须字母数字组成。',
        'maxlength': '测点编码不能多于50个字符长度。',
        'exist': '测点编码已存在。',
      },
      'tagKey': {
        'required': '测点Key不能为空。',
        'pattern': '测点Key必须字母数字组成。',
        'maxlength': '测点Key不能多于50个字符长度。',
        'exist': '测点编码已存在。',
      },
      'tagUnit': {
        'maxlength': '测点单位不能多于20个字符长度。',
      },
      'tagMin': {
        'maxNum': '数值不能大于65536可以保留两位小数'
      },
      'tagMax': {
        'maxNum': '数值不能大于65536可以保留两位小数'
      },
      'tagType': {
        'maxNum': '数值不能大于65536可以保留两位小数'
      }
    };
  }

  /**
   * 异步校验tagName，tagCode是否存在
   *
   * @param {FormControl} control
   * @returns {Promise<true>}
   *
   * @memberof tagEditComponent
   */
  tagAsnyValidator(control: FormControl, name: string, current: any): any {
    if (!control.value || control.value == current) {
      return Observable.of(null);
    }
    return this.tagService.hasTagName(control.value, this.currentEntity.tagId, name)
      .map(res => res ? {exist: true} : null);

  }

  /**
   * 创建一个测点信息
   *
   *
   * @memberof TurbstatusEditComponent
   */
  onCreate() {
    if (!this.hasError()) {
      this.changeCurrent();
      this.tagService.create(this.currentEntity)
        .then(res => {
          if (res) {
            const parentContainerInstance = this.parentBlade.bladeContainerInstance;
            parentContainerInstance.refresh(res);
            this.bladeService.closeBlade(this.currentBlade);
          } else {
            throw new Error('数据新增失败！')
          }
        })
        .catch(error => this.bladeData.error = error)
        .then(res => this.bladeData.isLoading = false);
    }
  }

  /**
   *
   *
   *
   * @memberof TagsEditComponent
   */
  saveChange(): any | Promise<any> | Observable<any> {
    if (this.canSaveChange(this.currentBlade)) {
      this.changeCurrent();
      return this.tagService.update(this.currentEntity)
        .then(res => {
          //  if (res) {
          this.clearText.emit(true);
          (this.parentBlade.bladeContainerInstance).refresh(res);
          this.bladeService.closeBlade(this.currentBlade);
          //  return true;
          //  }
          // throw new Error('数据更新失败！')

        })
        .catch(error => this.bladeData.error = error)
        .then(res => this.bladeData.isLoading = false);
    }
  }

  changeCurrent() {
    this.bladeData.isLoading = true;
    const formValue = this.formGroup.value;
    const arr = [];

    this.tagSets.forEach((value: Setofvalue, i: number) => {
      // tslint:disable-next-line:no-unused-expression
      formValue[value.valueCode] && arr.push(value.valueCode);
    });

    this.currentEntity.tagName = formValue.tagName;
    this.currentEntity.tagDesc = formValue.tagDesc;
    this.currentEntity.tagCode = formValue.tagCode;
    this.currentEntity.tagKey = formValue.tagKey;
    this.currentEntity.tagUnit = formValue.tagUnit;
    this.currentEntity.turbComponentId = formValue.turbComponentId;
    this.currentEntity.tagMin = formValue.tagMin;
    this.currentEntity.tagMax = formValue.tagMax;
    this.currentEntity.tagKind = formValue.tagKind;
    this.currentEntity.tagSet = arr.join('|');
    this.currentEntity.tagType = this.tagTypeId;

    // this.currentEntity.tagDefinition = !this.tagDefinition;
  }

  /**
   * 是否存在变更
   *
   * @returns {boolean}
   *
   * @memberof BladeContainerBase
   */
  hasChange(): boolean {

    if (this.formGroup != null) {
      const enity = this.formGroup.value;
      const names: string[] = Object.getOwnPropertyNames(enity);
      for (let i = 0; i < names.length; i++) {
        const name = names[i];
        if (this.tagForm.hasOwnProperty(name)) {
          const value = Object.getOwnPropertyDescriptor(this.tagForm, name).value;
          if (value != enity[name]) {
            return true;
          }
        }
      }
    }
    return false;
  }

// tslint:disable-next-line:eofline

  onTagTypeIsChecked(check: boolean, valueCode: string) {
    this.tagTypeId = valueCode;
    this.currentEntity.tagType = valueCode;
  }
}


// WEBPACK FOOTER //
// ./src/app/module/basic/tag/tag-edit/tag-edit.component.ts
